home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / cuj0593.zip / 1105101A < prev    next >
Text File  |  1993-03-09  |  2KB  |  66 lines

  1. /* records.c: Illustrates file positioning */
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6.  
  7. #define MAXRECS 10
  8.  
  9. struct record
  10. {
  11.     char last[16];
  12.     char first[11];
  13.     int age;
  14. };
  15.  
  16. static char *get_field(char *, char *);
  17.  
  18. main()
  19. {
  20.     int nrecs;
  21.     char s[81];
  22.     struct record recs[MAXRECS], recbuf;
  23.     FILE *f;
  24.  
  25.     /* Carefully store records */
  26.     for (
  27.          nrecs = 0;
  28.          nrecs < MAXRECS && get_field("Last",s);
  29.          ++nrecs
  30.         )
  31.     {
  32.         strncpy(recs[nrecs].last,s,15)[15] = '\0';
  33.         get_field("First",s);
  34.         strncpy(recs[nrecs].first,s,10)[10] = '\0';
  35.         get_field("Age",s);
  36.         recs[nrecs].age = atoi(s);
  37.     }
  38.  
  39.     /* Write records to file */
  40.     if ((f = fopen("recs.dat","w+b")) == NULL)
  41.         return EXIT_FAILURE;
  42.     if (fwrite(recs,sizeof recs[0],nrecs,f) != nrecs)
  43.         return EXIT_FAILURE;
  44.  
  45.     /* Position at last record */
  46.     fseek(f,(nrecs-1)*sizeof(struct record),SEEK_SET);
  47.     fread(&recbuf,1,sizeof(struct record),f);
  48.     printf("last: %s, first: %s, age: %d\n",
  49.       recbuf.last,recbuf.first,recbuf.age);
  50.  
  51.     /* Position at first record */
  52.     rewind(f);
  53.     fread(&recbuf,1,sizeof(struct record),f);
  54.     printf("last: %s, first: %s, age: %d\n",
  55.       recbuf.last,recbuf.first,recbuf.age);
  56.  
  57.     return EXIT_SUCCESS;
  58. }
  59.  
  60. static char *get_field(char *prompt, char *buf)
  61. {
  62.     /* Prompt for input field */
  63.     fprintf(stderr,"%s: ",prompt);
  64.     return gets(buf);
  65. }
  66.